import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //当前点击商品的id
    CurrentGoodsId:'',
    //购物车数据
    car:[],
    //商品总价
    total:0,
    imginfo:[]
  },
  mutations: {
    //设置访问news的页面
    setNewsId(state,id){
      state.id = id
    },
    //设置当前点击商品的id
    setCurrentGoodsId(state,id){
      state.CurrentGoodsId = id;
      window.sessionStorage.setItem('CurrentGoodsId',JSON.stringify(state.CurrentGoodsId))
      console.log("-------");
      
    },
    //购物车新加商品
    addToCar(state,prame){
      state.car.push(prame)
      window.localStorage.setItem('car',JSON.stringify(state.car)) 
    },
    //初始化购物车
    initCar(state,prame){
      const result = JSON.parse(window.localStorage.getItem("car"));
      state.car = result === null?[]:result
    },
    //购物车修改商品
    setCar(state,prame){
      //根据参数查找要添加商品在car数组中的索引值
      const index = state.car.findIndex(item => item.id === prame.id)
      if(prame.isAdd){
        state.car[index].count += prame.count;
      }else{
        state.car[index].count = prame.count;
      }
      
      window.localStorage.setItem('car',JSON.stringify(state.car)) 
    },
    //购物复选框是否选中
    goodsIsSel(state,prame){
         let i = state.car.findIndex(item => item.id === prame);
         state.car[i].selected = !state.car[i].selected;
         //更新数据到本地
         window.localStorage.setItem('car',JSON.stringify(state.car)) 
    },
    //全选按钮
    setAllSel(state,params){
        state.car.forEach(item => item.selected = !params)
        //更新数据到本地
        window.localStorage.setItem('car',JSON.stringify(state.car)) 
    },
    //同步商品的选中状态
    updateSel(state,prame){
      const i = state.car.findIndex(item => item.id == prame)
      state.car[i].selected = !state.car[i].selected;
    }
    
  },
  actions: {
  
  },
  modules: {
  },
  getters:{
    getTotal(state){
      
      let a = 0
      if(state.car.length !== 0){
        state.car.forEach(item => {
          if(item.selected){
          a += item.count * item.price
          }
        })
      }
      return a
    },
    getCounts(state){
      let counts = 0
      if(state.car.length !== 0){
        state.car.forEach(item => {
          counts += item.count;
        })
      }
      return counts
    },
    getIsAllSel(state){
      const isAllSel = state.car.every(item => item.selected);
      return isAllSel
    }
  }
})
